//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.stock.inventory;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import org.jpgolay.gui.fixed.SearchBox;
import org.jpgolay.gui.fixed.TableViewer;
import org.jpgolay.me.batch.Batch;
import org.jpgolay.me.persistence.ObjectCRUD;
import org.jpgolay.me.persistence.SQLList;
import org.jpgolay.me.util.*;

// Referenced classes of package org.jpgolay.me.stock.inventory:
//            InventoryListPanel
public class InventoryListController {

    public InventoryListController(InventoryListPanel inventoryListPanel, Parameter param) {
        updateRow = true;
        write = false;
        this.inventoryListPanel = inventoryListPanel;
        this.param = param;
        desktop = param.getDesktop();
        sqlList = new SQLList();
        crud = new ObjectCRUD();
        date = new MEDate();
        initLaw();
        initBatchListPanel();
    }

    private void initLaw() {
        if (param.getAccessLaw().length() >= 27 && param.getAccessLaw().charAt(27) == '1') {
            write = true;
        }
    }

    private void initBatchListPanel() {
        inventoryListPanel.getSearch().setVal("");
        inventoryListPanel.getSearch().setList(new String[]{
                    "N\260 DE LOT", "CODE ARTICLE", "GTIN ARTICLE", "CODE FOURN", "GLN FOURN", "CODE AGENCE", "N\260 CDS", "BL FOURN", "DLC", "DLUO",
                    "SSCC", "GTIN PALET", "GTIN CART"
                });
        inventoryListPanel.getSearch().setSelectedIndex(0);
        inventoryListPanel.getSearch().getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
        inventoryListPanel.getSearch().getTextField().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
        inventoryListPanel.getPrintLabel().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionPrint();
            }
        });
        inventoryListPanel.getTable().setTypes(new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.math.BigDecimal.class, java.math.BigDecimal.class, java.math.BigDecimal.class
                });
        inventoryListPanel.getTable().setLastColumnNotEditable(5);
        inventoryListPanel.getTable().setCellEditable(write);
        inventoryListPanel.getTable().setAlternateColor(MEUtility.BATCH_LINE);
        inventoryListPanel.getTable().setColumnNames(new String[]{
                    "N\260", "Ag", "N\260 Lot", "Code Art", "Date Inv", "Qt r\351el", "Qt phys", "Ecart"
                });
        inventoryListPanel.getTable().setPreferredColumnSize(new int[]{
                    20, 10, 40, 50, 50, 50, 50, 50
                });
        actionSearch();
    }

    private Object[][] getDataEmpty() {
        Object data[][] = new Object[3][8];
        for (int i = 0; i < data.length; i++) {
            data[i][0] = null;
            if (i == 1) {
                data[i][1] = "AUCUN";
                data[i][2] = "LOT";
            } else {
                data[i][1] = null;
                data[i][2] = null;
            }
            data[i][3] = null;
            data[i][4] = null;
            data[i][5] = null;
            data[i][6] = null;
            data[i][7] = null;
        }

        return data;
    }

    private void actionSearch() {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT id,agency_id,item_batch,item_id,inventory_date,stock_quantity,(stock_quantity - delta_inventory) as stk_physique, delta_inventory FROM batch");
        switch (inventoryListPanel.getSearch().getSelectedIndex()) {
            case 0: // '\0'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY item_batch");
                } else {
                    sql.append(" WHERE item_batch=");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append(" ORDER BY item_batch");
                }
                break;

            case 1: // '\001'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY item_id");
                } else {
                    sql.append(" WHERE item_id LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY item_id");
                }
                break;

            case 2: // '\002'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY item_gtin");
                } else {
                    sql.append(" WHERE item_gtin LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY item_gtin");
                }
                break;

            case 3: // '\003'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY supplier_id");
                } else {
                    sql.append(" WHERE supplier_id LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY supplier_id");
                }
                break;

            case 4: // '\004'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY supplier_gln");
                } else {
                    sql.append(" WHERE supplier_gln LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY supplier_gln");
                }
                break;

            case 5: // '\005'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY agency_id");
                } else {
                    sql.append(" WHERE agency_id=");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append(" ORDER BY agency_id");
                }
                break;

            case 6: // '\006'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY buy_id");
                } else {
                    sql.append(" WHERE buy_id LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY buy_id");
                }
                break;

            case 7: // '\007'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY delivery_form");
                } else {
                    sql.append(" WHERE delivery_form LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY delivery_form");
                }
                break;

            case 8: // '\b'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY dlc");
                } else {
                    sql.append(" WHERE dlc LIKE '");
                    sql.append(date.toMysql(inventoryListPanel.getSearch().getVal()));
                    sql.append("%' ORDER BY dlc");
                }
                break;

            case 9: // '\t'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY dluo");
                } else {
                    sql.append(" WHERE dluo LIKE '");
                    sql.append(date.toMysql(inventoryListPanel.getSearch().getVal()));
                    sql.append("%' ORDER BY dluo");
                }
                break;

            case 10: // '\n'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY sscc");
                } else {
                    sql.append(" WHERE sscc LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY sscc");
                }
                break;

            case 11: // '\013'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY pallet_gtin");
                } else {
                    sql.append(" WHERE pallet_gtin LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY pallet_gtin");
                }
                break;

            case 12: // '\f'
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY box_gtin");
                } else {
                    sql.append(" WHERE box_gtin LIKE '");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append("%' ORDER BY box_gtin");
                }
                break;

            default:
                if (inventoryListPanel.getSearch().getVal().equals("")) {
                    sql.append(" ORDER BY id");
                } else {
                    sql.append(" WHERE id=");
                    sql.append(inventoryListPanel.getSearch().getVal());
                    sql.append(" ORDER BY id");
                }
                break;
        }
        Object data[][] = (Object[][]) null;
        if (sqlList.search(sql.toString())) {
            data = sqlList.getRowsData();
            for (int i = 0; i < data.length; i++) {
                data[i][4] = date.toME((String) data[i][4]);
                data[i][5] = (new BigDecimal((String) data[i][5])).setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue());
                data[i][6] = (new BigDecimal((String) data[i][6])).setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue());
                data[i][7] = (new BigDecimal((String) data[i][7])).setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue());
            }

        }
        if (data != null) {
            inventoryListPanel.getTable().setData(data);
            inventoryListPanel.getTable().getTableModel().addTableModelListener(new TableModelListener() {
                public void tableChanged(TableModelEvent e) {
                    if (updateRow) {
                        actionUpdateRow(e.getFirstRow());
                    }
                }
            });
            inventoryListPanel.getSearch().setVal("");
        } else {
            inventoryListPanel.getTable().setData(getDataEmpty());
            JOptionPane.showMessageDialog(null, "Aucune donn\351es de correspondent \340 votre recherche !");
        }
    }

    private void actionPrint() {
    }

    private void actionUpdateRow(int row) {
        BigDecimal delta = (BigDecimal) inventoryListPanel.getTable().getTable().getValueAt(row, 7);
        BigDecimal stockPhysic = (BigDecimal) inventoryListPanel.getTable().getTable().getValueAt(row, 6);
        BigDecimal stockReel = (BigDecimal) inventoryListPanel.getTable().getTable().getValueAt(row, 5);
        Batch batch = (Batch) crud.read(new Integer((String) inventoryListPanel.getTable().getTable().getValueAt(row, 0)), 31);
        if (batch != null) {
            batch.setInventoryDate(date.getPlain());
            if (batch.getDeltaInventory().compareTo(delta) == 0) {
                delta = stockReel.subtract(stockPhysic);
            } else {
                stockPhysic = stockReel.subtract(delta);
            }
            batch.setDeltaInventory(delta);
            if (crud.update(batch, 31)) {
                updateRow = false;
                inventoryListPanel.getTable().getTable().setValueAt(delta, row, 7);
                inventoryListPanel.getTable().getTable().setValueAt(stockPhysic, row, 6);
                inventoryListPanel.getTable().getTable().setValueAt(batch.getInventoryDate(), row, 4);
                updateRow = true;
            } else {
                JOptionPane.showMessageDialog(null, "Enregistrement de la ligne d'inventaire \340 \351chou\351 !\n(Un utilisateur a peut-\352tre modifier cette ligne entre temps)");
            }
        }
    }
    private InventoryListPanel inventoryListPanel;
    private Parameter param;
    private JDesktopPane desktop;
    private SQLList sqlList;
    private MEDate date;
    private ObjectCRUD crud;
    private boolean updateRow;
    private boolean write;
}
